package com.taotao.rest.controller;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.pojo.TbUser;
import com.taotao.rest.pojo.CartItem;
import com.taotao.rest.pojo.Order;
import com.taotao.rest.service.CartService;
import com.taotao.rest.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "订单")
@RestController
public class OrderController {

    @Autowired
    private CartService cartService;

    @Autowired
    private OrderService orderService;

    @ApiOperation("将购物车商品转化为订单信息")
    @GetMapping({"/order/order-cart",
            "/rest/order/order-cart"})
    public TaotaoResult showOrderCart(HttpServletRequest request, HttpServletResponse response, Model model) {
        //取购物车商品列表
        List<CartItem> list = cartService.getCartItemList(request, response);
        return TaotaoResult.ok(list);
//        //传递给页面
//        model.addAttribute("cartList", list);
//
//        return "order-cart";
    }

    @ApiOperation("创建订单")
    @PostMapping({"/order/create", "/rest/order/create"})
    public TaotaoResult createOrder(Order order, Model model, HttpServletRequest request) {
        try {
            //从Request中取用户信息
            TbUser user = (TbUser) request.getAttribute("user");
            //在order对象中补全用户信息
            order.setUserId(user.getId());
            order.setBuyerNick(user.getUsername());
            //调用服务
            String orderId = orderService.createOrder(order);
            Map<String, Object> result = new HashMap<>();
            result.put("orderId", orderId);
            result.put("payment", order.getPayment());
            result.put("date", new DateTime().plusDays(3).toString("yyyy-MM-dd"));
            return TaotaoResult.ok(result);
//            model.addAttribute("orderId", orderId);
//            model.addAttribute("payment", order.getPayment());
//            model.addAttribute("date", new DateTime().plusDays(3).toString("yyyy-MM-dd"));
//            return "success";

        } catch (Exception e) {
            return TaotaoResult.build(510, "创建订单出错。请稍后重试！");
//            e.printStackTrace();
//            model.addAttribute("message", "创建订单出错。请稍后重试！");
//            return "error/exception";
        }
    }

}
